/**
 * 添加新的地址.//修改地址
 */
'use strict'
import React ,{Component} from 'react';
import Util from '../common/util'
import * as URLConstant from '../constant/URLconstant';//接口类
import Toast from '../common/ToastUtil';
import Header from '../common/header';
import styles from './style/addAddressStyle';
import Modal from 'react-native-modalbox';
import * as StringUtils from '../common/StringUtil';
import  MyStroage from '../common/myStroage';//异步存储
import {
    StyleSheet,
    View,
    Text,
    TextInput,
    TouchableOpacity,
    Picker,
}from 'react-native';
export default class addModifyAddress extends Component {
    // 构造
    constructor(props) {
        super(props);
        this.provinceSuccessCallback = this.provinceSuccessCallback.bind(this);
        this.failCallback = this.failCallback.bind(this);
        this.closeCityModal = this.closeCityModal.bind(this);
        this.citySuccessCallback = this.citySuccessCallback.bind(this);
        this.countySuccessCallback = this.countySuccessCallback.bind(this);
        // 初始状态
        this.state = {
            editable: true,
            isCityModalOpen: false,
            provinceData: '',
            isModal: false,
            province_id: 0,
            cityData: '',
            countyData: '',
            id: 0,
        };
    }

    async componentDidMount() {
        let params = this.props.route.params
        this.params = params
        let that = this;
        try {
            let userInfoDate = await MyStroage.getStorageAllDataForKey('userinfo');
            if (userInfoDate != null) {
                let user_id = userInfoDate.data.user_id;
                if (user_id != null || user_id != '') {
                    that.setState({user_id: user_id});
                    this.initAddressData();
                }
            }
        } catch (err) {
            //LOG('新增地址===' + err);
        }
    }

    //初始化页面的值
    initAddressData() {
        let that = this;
        that.getAddressData(0);
        let type = this.params.id;
        let title, ConsigneeName, cellphone, final_region_name, address, region_id;
        if (type == 1) {
            title = '新增收货地址' , ConsigneeName = '收货用户名',
                cellphone = '11位手机号', final_region_name = '点击选择', address = '详细地址';
        } else if (type == 2) {
            let rowData = this.params.rowData;
            title = '修改收货地址', ConsigneeName = rowData.consignee,
                cellphone = rowData.phone_mob, final_region_name = rowData.region_name,
                address = rowData.address, region_id = rowData.region_id;
        }
        that.setState({
            autoFocus: true,//获取焦点
            title: title,
            ConsigneeName: ConsigneeName,//收货人姓名
            cellphone: cellphone,//手机号
            final_region_name: final_region_name,//地址选择
            address: address,//详细地址
            region_id: region_id,
        });
    }

    //获取地区的方法
    getAddressData(id, parent_id) {
        let that = this;
        let url = URLConstant.REGION_ADDRESS_URL;
        let data = [];
        if (0 == id) {
            Util.get(url, data, that.provinceSuccessCallback, that.failCallback);
        } else if (1 == id) {
            data['parent_id'] = parent_id
            Util.get(url, data, that.citySuccessCallback, that.failCallback);
        } else if (2 == id) {
            data['parent_id'] = parent_id;
            Util.get(url, data, that.countySuccessCallback, that.failCallback);
        }
    }

    //获取一级省数据
    provinceSuccessCallback(datas) {
        let that = this;
        let data = datas['data'];
        if (datas['status'] == 0) {
            that.setState({
                provinceData: data,
                isModal: true,
            });
        }
    }

    //获取二级市数据
    citySuccessCallback(datas) {
        let that = this;
        let data = datas['data'];
        if (datas['status'] == 0) {
            that.setState({
                cityData: data,
            });
        }
    }

    //获取三级县数据
    countySuccessCallback(datas) {
        let that = this;
        let data = datas['data'];
        if (datas['status'] == 0) {
            that.setState({
                countyData: data,
            });
        }
    }

    failCallback(err) {
        LOG('REGION====' + err);
    }

    //一级数据省ui界面
    provinceMethod() {
        return (
            <Picker
                style={{ width: Util.size.width / 3}}
                itemStyle={{fontSize:12,}}
                selectedValue={this.state.province_id}
                onValueChange={(province_id) => this.openSecondModal(province_id) }>
                {this.showProvice()}
            </Picker>
        )
    }

    //显示省一级分类的子项
    showProvice() {
        let that = this;
        let proviceList = that.state.provinceData;
        if (proviceList == '' || proviceList == null) {
            return
        }
        let list = [];
        let row;
        row = (  <Picker.Item label="--请选择--" value="-999" key={0}/>);
        list.push(row);
        for (let i in proviceList) {
            row = (
                <Picker.Item label={proviceList[i].region_name} value={proviceList[i].region_id} key={i}/>
            )
            list.push(row);
        }
        return list;
    }

    //选择省id的方法
    openSecondModal(province_id) {
        let that = this;
        that.setState({
            province_id: province_id,
            city_id: 0,
            county_id: 0,
            countyData: '',
        });
        that.finalRegionName();
        that.getAddressData(1, province_id);
    }

    //二级市区ui界面
    cityMethod() {
        let that = this;
        let cityData = that.state.cityData;
        if (cityData != null && cityData.length > 0 && cityData != '') {
            return (
                <Picker
                    style={{ width: Util.size.width / 3, }}
                    itemStyle={{fontSize:12,}}
                    selectedValue={this.state.city_id}
                    onValueChange={(city_id) => this.openThirdModal(city_id) }>
                    {this.showSecondCity()}
                </Picker>
            )
        } else {
            return;
        }
    }

    //二级城市数据的详细信息
    showSecondCity() {
        let that = this;
        let cityList = that.state.cityData;//市一级
        if (cityList == null || cityList == "" || cityList.length <= 0) {
            return;
        }
        let row;
        let list = [];
        row = ( <Picker.Item label="--请选择 --" value="-999" key={0}/>);
        list.push(row);
        for (let i in cityList) {
            row = (
                <Picker.Item label={cityList[i].region_name} value={cityList[i].region_id} key={i}/>
            )
            list.push(row);
        }
        return list;
    }

    //二级选择市区id的方法
    openThirdModal(city_id) {
        let that = this;
        that.setState({
            city_id: city_id,
            county_id: 0,
        });
        that.finalRegionName();
        that.getAddressData(2, city_id);

    }

    //三级县ui界面
    countyMethod() {
        let countyList = this.state.countyData;
        if (countyList != null && countyList.length > 0 && countyList != '') {
            return (
                <Picker
                    style={{ width: Util.size.width / 3, }}
                    itemStyle={{fontSize:12,}}
                    selectedValue={this.state.county_id}
                    onValueChange={(county_id) => this.onValueChange(county_id) }>
                    {this.showThirdCity()}
                </Picker>);

        } else {
            return null;
        }
    }

    //三级城市数据的详细信息
    showThirdCity() {
        let that = this;
        let countyList = that.state.countyData;//第三级数据
        if (countyList == null || countyList == "" || countyList.length <= 0) {
            return;
        }
        let list = [];
        let row;
        row = (  <Picker.Item label="--请选择--" value="-999" key={0}/>);
        list.push(row);
        for (let i in countyList) {
            row = (
                <Picker.Item label={countyList[i].region_name} value={countyList[i].region_id} key={i}/>
            )
            list.push(row);
        }
        return list;
    }

    async onValueChange(county_id) {
        try {
            let that = this;
            await that.setState({
                county_id: county_id,
            });
            that.finalRegionName();
        } catch (err) {
            LOG(err);
        }

    }

    //用于显示所在地区
    finalRegionName() {
        let that = this;
        let proviceList = that.state.provinceData;//省一级
        let province_id = that.state.province_id;
        let cityList = that.state.cityData;//市二级
        let city_id = that.state.city_id;
        let countyList = that.state.countyData;//第三级数据
        let county_id = that.state.county_id;
        let finalRegionName = '点击选择';
        let province_name;
        let region_id;
        if (proviceList != null && proviceList != '' && proviceList.length > 0) {
            for (let i in proviceList) {
                if (province_id == proviceList[i].region_id) {
                    province_name = proviceList[i].region_name;
                    region_id = province_id;
                }
            }
        }
        if (cityList != null && cityList != '' && cityList.length > 0) {
            for (let i in cityList) {
                if (city_id == cityList[i].region_id) {
                    finalRegionName = province_name + cityList[i].region_name;
                    region_id = city_id
                }
            }
        }
        if (countyList != null && countyList != '' && countyList.length > 0) {
            for (let i in countyList) {
                if (county_id == countyList[i].region_id) {
                    finalRegionName = finalRegionName + countyList[i].region_name;
                    region_id = county_id
                }
            }
        }
        that.setState({
            final_region_name: finalRegionName,
            region_id: region_id
        });
    }


    //打开地址选择器
    openCityModal() {
        let that = this;
        let isModal = this.state.isModal;
        if (isModal) {
            that.setState({
                isCityModalOpen: true,
                editable: false,
            });
        }
    }

    //地址选择框
    showAddressModal() {
        return (
            <Modal isOpen={this.state.isCityModalOpen}
                   style={styles.city_modal}
                   swipeToClose={false} backdropOpacity={0.3}
                   position={"bottom"} backdropPressToClose={false}>
                <View style={styles.modal_btn}>
                    <TouchableOpacity onPress={() => this.closeCityModal(1) }>
                        <Text style={{color:'#ff1493',fontSize:15}}>取消</Text>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => this.closeCityModal(2) }>
                        <Text style={{color:'#ff1493',fontSize:15}}>确定</Text>
                    </TouchableOpacity>
                </View>
                <View style={{flexDirection:"row"}}>
                    {/*一级省选择器的方法*/}
                    {this.provinceMethod()}
                    {/*二级市区选择器的方法*/}
                    {this.cityMethod()}
                    {/*三级县选择器的方法*/}
                    {this.countyMethod()}
                </View>
            </Modal>
        );
    }

    //取消确定地址选择
    closeCityModal(id) {
        let that = this;
        if (1 == id) {
            that.setState({
                isCityModalOpen: false,
                editable: true,
                final_region_name: '点击选择',
                region_id: -999,
                province_id: -999,
                cityData: '',
                countyData: ''
            });
        } else if (2 == id) {
            that.onSaveaddress();
        }
    }

    onSaveaddress() {
        let that = this;
        let final_region_name = that.state.final_region_name;
        let countyList = that.state.countyData;//第三级数据
        let county_id = that.state.county_id;
        //LOG('county_id====' + county_id);
        if (final_region_name == '点击选择') {
            Toast.show('亲,请选择完整的收货地址!');
            return;
        }
        if (countyList.length > 0 && county_id == 0 || county_id == -999) {
            Toast.show('亲,请选择完整的收货地址!');
            return;
        }
        that.setState({
            isCityModalOpen: false,
            editable: true,
        });
    }

    //保存或者修改地址
    saveUserAdder() {
        let that = this;
        let type = this.params.id;
        let ConsigneeName = that.state.ConsigneeName;
        let cellphone = that.state.cellphone;
        let final_region_name = that.state.final_region_name;
        let address = that.state.address;
        let region_id = that.state.region_id;
        let rowData = this.params.rowData;
        let data = [];
        let addUrl;
        if (ConsigneeName == '收货用户名' || ConsigneeName == '') {
            Toast.show('亲,收货人不能为空!');
            return;
        } else if (StringUtils.isCellphone(cellphone) == false) {
            return;
        } else if (final_region_name == '点击选择') {
            Toast.show('亲,请选择完整的收货地址!');
            return;
        } else if (address == '详细地址' || address == '') {
            Toast.show('亲,详细地址不能为空!');
            return;
        }
        if (1 == type) {
            data['user_id'] = that.state.user_id;
            data['consignee'] = ConsigneeName;
            data['region_id'] = region_id;
            data['region_name'] = final_region_name;
            data['address'] = address;
            data['zipcode'] = '';
            data['phone_tel'] = '';
            data['phone_mob'] = cellphone;
            addUrl = URLConstant.ADD_ADDRESS_URL;
        } else {
            data['user_id'] = that.state.user_id;
            data['addr_id'] = rowData.addr_id;
            data['consignee'] = ConsigneeName;
            data['region_id'] = region_id;
            data['region_name'] = final_region_name;
            data['address'] = address;
            data['zipcode'] = '';
            data['phone_tel'] = '';
            data['phone_mob'] = cellphone;
            addUrl = URLConstant.UPDATE_ADDRESS_URL;
        }
        Util.post(addUrl, data, function (ret) {
                if (ret['status'] == 0) {
                    Toast.show(ret['msg']);
                    if (that.params.getOrderOnServer != null) {
                        that.params.getOrderOnServer(3);
                    }
                    that.props.navigation.pop();
                } else {
                    alert('添加不成功');
                }
            }, function (err) {
                LOG(err)
            }
        );
    }

    render() {
        let params = this.props.route.params
        return (
            <View style={{ flex: 1,backgroundColor:"#EEE" }}>
                <Header navigation={this.props.navigation} title={params.title}/>

                <View style={[styles.row,{marginTop:10}]}>
                    <Text style={styles.text1}>收货人: </Text>
                    <TextInput
                        style={styles.txt_input}
                        underlineColorAndroid="#fff"
                        autoCorrect={false}
                        enablesReturnKeyAutomatically={true}
                        returnKeyType='next'
                        autoFocus={this.state.autoFocus}
                        editable={this.state.editable}
                        onChange={(event) => this.setState({ConsigneeName:event.nativeEvent.text}) }
                        placeholder={this.state.ConsigneeName}
                        placeholderText="#ccc"/>
                </View>

                <View style={styles.row}>
                    <Text style={styles.text1}>联系方式: </Text>
                    <TextInput
                        style={styles.txt_input}
                        underlineColorAndroid="#fff"
                        autoCorrect={false}
                        maxLength={11}
                        editable={this.state.editable}
                        enablesReturnKeyAutomatically={true}
                        returnKeyType='next'
                        onChange={(event) => this.setState({cellphone:event.nativeEvent.text}) }
                        keyboardType="numeric"
                        placeholder={this.state.cellphone}
                        placeholderText="#ccc"/>
                </View>

                <TouchableOpacity onPress={() => this.openCityModal() }>
                    <View style={styles.row}>
                        <Text style={styles.text1}>所在地区: </Text>
                        <Text numberOfLines={1}
                              style={{color:"#ccc",fontSize:12,width:Util.size.width - 150}}>
                            {this.state.final_region_name}
                        </Text>
                    </View>
                </TouchableOpacity>

                <View style={styles.row}>
                    <Text style={styles.text1}>详细地址: </Text>
                    <TextInput
                        style={styles.txt_input}
                        underlineColorAndroid="#fff"
                        autoCorrect={false}
                        editable={this.state.editable}
                        onChangeText={(text) => this.setState({address:text})}
                        enablesReturnKeyAutomatically={true}
                        returnKeyType='next'
                        placeholder={this.state.address}
                        placeholderText="#ccc"/>
                </View>

                {/*保存新增或修改的按钮*/}
                <View style={styles.onClink_style}>
                    <TouchableOpacity onPress={() => this.saveUserAdder() }>
                        <View
                            style={styles.onClink_view}>
                            <Text style={styles.save}>保存{this.state.title}</Text>
                        </View>
                    </TouchableOpacity>
                </View>
                {/*地址选择框*/}
                {this.showAddressModal()}

            </View>
        )
    }

}